<template>
  <div>
    <!-- 新增与搜索区域 -->
    <div class="header-actions">
      <el-button @click="showAddDialog">新增题目</el-button>
      <el-input v-model="searchQuery" placeholder="搜索题目..." style="width: 200px;" />

      <!-- 筛选题库 -->
      <el-select v-model="selectedBankFilter" placeholder="全部题库" style="width: 150px;">
        <el-option label="全部题库" value="" />
        <el-option v-for="bank in banks" :key="bank.id" :label="bank.name" :value="bank.id" />
      </el-select>

      <!-- 筛选题型 -->
      <el-select v-model="selectedTypeFilter" placeholder="全部题型" style="width: 130px;">
        <el-option label="全部题型" value="" />
        <el-option label="单选题" value="SINGLE" />
        <el-option label="多选题" value="MULTIPLE" />
        <el-option label="判断题" value="JUDGE" />
      </el-select>
    </div>

    <!-- 添加表格容器ref -->
    <div ref="tableContainer">
      <el-table :data="displayedQuestions" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="60px"></el-table-column>
        <el-table-column prop="content" label="题目内容" width="500px"></el-table-column>
        
        <!-- 类型列：英文转中文 -->
        <el-table-column prop="type" label="类型" width="80px">
          <template #default="{ row }">
            <span>{{ questionTypeMap[row.type] }}</span>
          </template>
        </el-table-column>

        <!-- 选项列：JSON字符串转列表 -->
        <el-table-column label="选项">
          <template #default="{ row }">
            <div v-for="(option, index) in parseOptions(row.options)" :key="index">
              <span>{{ option }}</span>
            </div>
          </template>
        </el-table-column>

        <!-- 答案列 -->
        <el-table-column prop="answer" label="答案" width="60px"></el-table-column>

        <!-- 创建时间列 -->
        <el-table-column prop="createTime" label="创建时间">
          <template #default="{ row }">
            <span>{{ formatTime(row.createTime) }}</span>
          </template>
        </el-table-column>

        <!-- 操作列 -->
        <el-table-column label="操作" width="150px">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="editQuestion(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteQuestion(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 新增对话框 -->
    <el-dialog v-model="addDialogVisible" title="新增题目">
      <el-form :model="newQuestionForm" label-width="100px">
        <el-form-item label="所属题库">
          <el-select v-model="newQuestionForm.bankId" placeholder="请选择题库">
            <el-option v-for="bank in banks" :key="bank.id" :label="bank.name" :value="bank.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="题目类型">
          <el-select v-model="newQuestionForm.type" placeholder="请选择类型">
            <el-option label="单选题" value="SINGLE" />
            <el-option label="多选题" value="MULTIPLE" />
            <el-option label="判断题" value="JUDGE" />
          </el-select>
        </el-form-item>

        <el-form-item label="题目内容">
          <el-input v-model="newQuestionForm.content" type="textarea" :rows="3" />
        </el-form-item>

        <el-form-item label="题目选项">
          <el-input v-model="newQuestionForm.rawOptions" type="textarea" :rows="5"
            placeholder="请输入选项，每行一个，例如：&#10;A. 正确&#10;B. 错误" />
        </el-form-item>

        <el-form-item label="答案">
          <el-input v-model="newQuestionForm.answer" placeholder="例如：A / B / C / D" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAddQuestion">确定新增</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="editDialogVisible" title="编辑题目">
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="所属题库">
          <el-select v-model="editForm.bankId" placeholder="请选择题库">
            <el-option v-for="bank in banks" :key="bank.id" :label="bank.name" :value="bank.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="题目类型">
          <el-select v-model="editForm.type" placeholder="请选择类型">
            <el-option label="单选题" value="SINGLE" />
            <el-option label="多选题" value="MULTIPLE" />
            <el-option label="判断题" value="JUDGE" />
          </el-select>
        </el-form-item>

        <el-form-item label="题目内容">
          <el-input v-model="editForm.content" type="textarea" :rows="3" />
        </el-form-item>

        <el-form-item label="题目选项">
          <el-input v-model="editForm.rawOptions" type="textarea" :rows="5"
            placeholder="请输入选项，每行一个，例如：&#10;A. 正确&#10;B. 错误" />
        </el-form-item>

        <el-form-item label="答案">
          <el-input v-model="editForm.answer" placeholder="例如：A / B / C / D" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit">保存修改</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import api from '../services/api';
import { ElLoading, ElMessageBox, ElMessage } from 'element-plus';

const questions = ref([]);
const selectedBankFilter = ref(''); // 当前选中的题库（null 表示全部）
const selectedTypeFilter = ref(''); // 当前选中的题型（null 表示全部）
const searchQuery = ref('');
const editDialogVisible = ref(false);
const editForm = ref({
  id: '',
  bankId: '',
  type: '',
  content: '',
  options: '[]',
  answer: '',
  rawOptions: '', // 编辑时用于显示原始字符串格式的选项
});
const addDialogVisible = ref(false);
const newQuestionForm = ref({
  bankId: '',
  type: '',
  content: '',
  rawOptions: '',  // 新增 rawOptions 字段
  answer: '',
});
const banks = ref([]); // 所有题库列表

function showAddDialog() {
  addDialogVisible.value = true;
}
async function fetchBanks() {
  const res = await api.getAllBanks();
  banks.value = res.data;
}

async function submitAddQuestion() {
  try {
    const questionData = {
      bankId: newQuestionForm.value.bankId,
      type: newQuestionForm.value.type,
      content: newQuestionForm.value.content,
      options: parsedOptions.value,
      answer: newQuestionForm.value.answer.trim().toUpperCase(), // 答案自动转大写
      createTime: new Date(new Date().getTime() - new Date().getTimezoneOffset() * 60000).toISOString(),
    };

    await api.createQuestion(questionData);
    addDialogVisible.value = false;
    newQuestionForm.value = {
      bankId: '',
      type: '',
      content: '',
      rawOptions: '',
      answer: ''
    };
    await fetchQuestions(); // 重新加载当前筛选下的数据
    displayedQuestions.value = filterQuestions(); // 手动更新显示数据
    ElMessage.success('题目新增成功'); // 新增成功提示
  } catch (error) {
    console.error('新增题目失败:', error);
    ElMessage.error('新增题目失败'); // 新增失败提示
  }
}

function editQuestion(row) {
  // 复制 row 数据到 editForm
  editForm.value = {
    ...row,
    rawOptions: parseRawOptionsToString(row.options), // 将 JSON 数组转为换行字符串
  };
  editDialogVisible.value = true;
}

function parseRawOptionsToString(optionsStr) {
  try {
    const arr = JSON.parse(optionsStr);
    return arr.join('\n');
  } catch (e) {
    return '';
  }
}

function parseRawOptions(rawOptions) {
  if (!rawOptions) return '[]';

  const lines = rawOptions
    .split('\n')
    .map(line => line.trim())
    .filter(Boolean)
    .map(line => line.charAt(0).toUpperCase() + line.slice(1));

  return JSON.stringify(lines);
}

async function submitEdit() {
  try {
    // 构造最终要提交的数据
    const updatedData = {
      id: editForm.value.id,
      bankId: editForm.value.bankId,
      type: editForm.value.type,
      content: editForm.value.content,
      answer: editForm.value.answer.trim().toUpperCase(),
      options: parseRawOptions(editForm.value.rawOptions),
    };

    await api.updateQuestion(updatedData); // 调用接口更新数据
    editDialogVisible.value = false; // 关闭弹窗
    await fetchQuestions(); // 重新获取数据
    displayedQuestions.value = filterQuestions(); // 更新显示列表
    ElMessage.success('题目修改成功'); // 新增成功提示
  } catch (error) {
    console.error('编辑题目失败:', error);
    ElMessage.error('题目修改失败'); // 新增失败提示
  }
}

async function deleteQuestion(id) {
  try {
    await ElMessageBox.confirm('确定删除该题目？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    await api.deleteQuestion(id);
    await fetchQuestions();
    displayedQuestions.value = filterQuestions();
    ElMessage.success('题目删除成功');
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error('题目删除失败');
    }
  }
}

async function fetchQuestions() {
  // 如果题库和题型都是空字符串，则视为“全部”
  if (selectedBankFilter.value === '' && selectedTypeFilter.value === '') {
    const res = await api.getAllQuestions();
    questions.value = res.data;
    return;
  }

  // 直接传递原始值，不再转换 undefined
  const bankId = selectedBankFilter.value;
  const type = selectedTypeFilter.value;

  const res = await api.getQuestionsByBankAndType(bankId, type);
  questions.value = res.data;
}

const questionTypeMap = {
  SINGLE: '单选题',
  JUDGE: '判断题',
  MULTIPLE: '多选题'
};

function parseOptions(optionsStr) {
  try {
    return JSON.parse(optionsStr);
  } catch (e) {
    return [];
  }
}

const parsedOptions = computed(() => {
  if (!newQuestionForm.value.rawOptions) return '[]';

  const lines = newQuestionForm.value.rawOptions
    .split('\n')
    .map(line => {
      if (!line.trim()) return null;

      // 只转换第一个字符为大写，其余不变
      return line.charAt(0).toUpperCase() + line.slice(1);
    })
    .filter(line => line !== null);

  return JSON.stringify(lines);
});

function filterQuestions() {
  let result = [...questions.value];

  if (selectedBankFilter.value !== '') {
    result = result.filter(q => q.bankId == selectedBankFilter.value);
  }

  if (selectedTypeFilter.value !== '') {
    result = result.filter(q => q.type === selectedTypeFilter.value);
  }

  if (searchQuery.value.trim()) {
    const keyword = searchQuery.value.toLowerCase();
    result = result.filter(q => q.content.toLowerCase().includes(keyword));
  }

  return result;
}

const displayedQuestions = ref([]);

watch(
  () => [selectedBankFilter.value, selectedTypeFilter.value, searchQuery.value],
  async () => {
    await fetchQuestions();
    displayedQuestions.value = filterQuestions();
  },
  { immediate: true }
);
function formatTime(timeStr) {
  const date = new Date(timeStr);
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
}

const tableContainer = ref(null);  // 添加表格容器ref

onMounted(async () => {
  const loading = ElLoading.service({
    lock: false,
    target: tableContainer.value,
    text: '数据加载中',
    background: 'rgba(0, 0, 0, 0.3)'
  });

  try {
    await Promise.all([fetchBanks(), fetchQuestions()]);
    setTimeout(() => loading.close(), 500);
  } catch (error) {
    loading.close();
    console.error('初始化数据失败:', error);
  }
});
</script>